<template>
  <div class="content">
    <div class="header">
      <el-select v-model="listQuery.unitDeptCode" clearable placeholder="请选择单位" class="form-top-p">
        <el-option
          v-for="item in deptList_dw"
          :key="item.deptNo"
          :label="item.deptName"
          :value="item.deptNo" />
      </el-select>
      <el-select
        v-model="listQuery.defectCategoryId"
        clearable
        placeholder="请选择缺陷分类"
        class="form-top-p">
        <el-option
          v-for="item in defectTypeList"
          :key="item.id"
          :label="item.categoryName"
          :value="item.id" />
      </el-select>
      <a-form-model-item label="年份" class="ele-input">
        <el-date-picker v-model="times.startYear" type="year" format="yyyy" value-format="yyyy" placeholder="选择开始年" @change="getYearList" />
        ～
        <el-date-picker v-model="times.endYear" type="year" format="yyyy" value-format="yyyy" placeholder="选择结束年" @change="getYearList" />
      </a-form-model-item>
      <el-button
        type="primary"
        style="margin-left:15px;"
        size="mini"
        icon="el-icon-search"
        @click="search">查询</el-button>
      <el-button
        style="background: #A7B7C9;color:#FFFFFF;"
        size="mini"
        icon="el-icon-refresh"
        @click="reset">重置</el-button>
    </div>
    <div class="main">
      <div class="main_div">
        <el-card class="box-card">
          <div
            slot="header"
            style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;">
            <div style="display:flex;align-items: center">
              <img src="@/assets/images/userInspetionCharts.png" style="margin-right:7px;" alt>
              <span
                style="margin-right:7px;">{{ getDefectTypeName(defectCategoryId) + ' 月度数据' }}</span>
            </div>

            <el-button type="primary" size="mini" icon="el-icon-download" @click="getImg1">导出图片</el-button>
          </div>
          <div ref="charts1" class="cardMain" />
        </el-card>
      </div>
      <div class="main_div">
        <el-card class="box-card">
          <div
            slot="header"
            style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;">
            <div style="display:flex;align-items: center">
              <img src="@/assets/images/line.png" style="margin-right:7px;" alt>
              <span
                style="margin-right:7px;">{{ getDefectTypeName(defectCategoryId) + ' 年度数据' }}</span>
            </div>

            <el-button type="primary" size="mini" icon="el-icon-download" @click="getImg2">导出图片</el-button>
          </div>
          <div ref="charts2" class="cardMain" />
        </el-card>
      </div>
      <div class="main_div">
        <el-card class="box-card">
          <div
            slot="header"
            style="display: flex;justify-content: space-between;width: 100%;height: 100%;align-items: center;">
            <div style="display:flex;align-items: center">
              <img src="@/assets/images/userInspetionCharts.png" style="margin-right:7px;" alt>
              <span
                style="margin-right:7px;">{{ getDefectTypeName(defectCategoryId) + ' 区站分布柱状分析图TOP10' }}</span>
            </div>

            <el-button type="primary" size="mini" icon="el-icon-download" @click="getImg3">导出图片</el-button>
          </div>
          <div ref="charts3" class="cardMain" />
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { findManageUnitDeptList, defectCategoryList } from '@/api/platform'
import { defectsSpecialAnalysis, siteDefectTop, lineDefectYear } from '@/api/cms/Analysis-management/synthetical-Analysis/unitDefect'
import echarts from 'echarts'
export default {
  data() {
    return {
      deptList_dw: [],
      defectTypeList: [],
      times: {
        startYear: (new Date().getFullYear() - 3).toString(),
        endYear: new Date().getFullYear().toString()
      },
      defectCategoryId: '',
      listQuery: {
        unitDeptCode: '',
        defectCategoryId: '',
        yearList: []
      }
    }
  },
  mounted() {
    this.getList()
    this.getYearList()
  },
  methods: {
    getList() {
      defectCategoryList().then((response) => {
        this.defectTypeList = response.data
        this.listQuery.defectCategoryId = response.data[0] ? response.data[0].id : ''
        this.search()
      })
      findManageUnitDeptList({}).then(response => {
        var resData = response.data
        for (var i in resData) {
          if (resData[i].deptNo === '001200') {
            resData.splice(i, 1)
          }
        }
        this.deptList_dw = resData
      })
    },
    search() {
      this.defectCategoryId = this.listQuery.defectCategoryId
      if (this.times.startYear > this.times.endYear) {
        this.$message({
          message: '开始时间不能大于结束时间',
          type: 'warning'
        })
      } else {
        this.getCherts1()
        this.getCherts2()
        this.getCherts3()
      }
    },
    reset() {
      this.listQuery = {
        unitDeptCode: '',
        defectCategoryId: this.defectTypeList[0] ? this.defectTypeList[0].id : '',
        yearList: [(new Date().getFullYear() - 3).toString(), (new Date().getFullYear() - 2).toString(), (new Date().getFullYear() - 1).toString(), new Date().getFullYear().toString()]
      }
      this.search()
    },
    getCherts1() {
      defectsSpecialAnalysis(this.listQuery).then(res => {
        var yData = []
        var legendData = Object.keys(res.data)
        for (const key in res.data) {
          yData.push({
            name: key,
            data: res.data[key],
            type: 'bar',
            barWidth: 20,
            stack: 'zs'
          })
        }
        const myChart = echarts.init(this.$refs.charts1)
        const options = {
          title: {
            text: this.getDeptName(this.listQuery.unitDeptCode),
            x: 'center',
            y: 10
          },
          tooltip: {
            trigger: 'item'
          },

          xAxis: {
            type: 'category',
            data: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
            axisLabel: {
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          legend: {
            top: '5%',
            right: '5%',
            icon: 'circle',
            itemWidth: 10, // 设置宽度
            itemHeight: 10, // 设置高度
            data: legendData
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '20%',
            top: '25%'
          },

          yAxis: {
            type: 'value',
            axisLabel: {
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          color: ['#3646FA', '#4493FB', '#57E5FD'],
          series: yData
        }
        console.log('options.series', options.series)
        myChart.clear()
        myChart.setOption(options)
      })
    },
    getImg1() {
      const myChart = echarts.init(this.$refs.charts1)
      const imgName = this.getDefectTypeName(this.defectCategoryId) + '月度数据'
      this.getImage('png', myChart, imgName)
    },
    getCherts2() {
      lineDefectYear(this.listQuery).then(res => {
        const xData = this.listQuery.yearList
        const yData = []
        const legendData = []

        const myChart = echarts.init(this.$refs.charts2)

        for (const key in res.data) {
          legendData.push(key)
          yData.push({
            name: key,
            data: res.data[key],
            type: 'line'
          })
        }

        const options = {
          title: {
            text: this.getDeptName(this.listQuery.unitDeptCode),
            x: 'center',
            y: 10
          },
          tooltip: {
            trigger: 'item'
          },

          xAxis: {
            type: 'category',
            data: xData,
            axisLabel: {
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          legend: {
            type: 'scroll',
            top: '5%',
            right: '5%',
            left: '70%',
            icon: 'circle',
            itemWidth: 10, // 设置宽度
            itemHeight: 10, // 设置高度
            data: legendData
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '20%',
            top: '25%'
          },

          yAxis: {
            type: 'value',
            axisLabel: {
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          color: ['#3646FA', '#4493FB', '#57E5FD'],
          series: yData
        }
        myChart.clear()
        myChart.setOption(options)
      })
    },
    getImg2() {
      const myChart = echarts.init(this.$refs.charts2)
      const imgName = this.getDefectTypeName(this.defectCategoryId) + '年度数据'
      this.getImage('png', myChart, imgName)
    },
    getCherts3() {
      siteDefectTop(this.listQuery).then(res => {
        var xData = []
        var yData = []
        var legendData = this.listQuery.yearList
        xData = res.data.siteName

        for (const key in res.data) {
          if (key !== 'siteName') {
            yData.push({
              name: key,
              data: res.data[key],
              type: 'bar',
              barWidth: 20,
              stack: 'zs'
            })
          }
        }
        const myChart = echarts.init(this.$refs.charts3)
        const options = {
          title: {
            text: this.getDeptName(this.listQuery.unitDeptCode),
            x: 'center',
            y: 10
          },
          tooltip: {
            trigger: 'item'
          },

          xAxis: {
            type: 'category',
            data: xData,
            axisLabel: {
              interval: 0,
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          legend: {
            top: '5%',
            right: '5%',
            icon: 'circle',
            itemWidth: 10, // 设置宽度
            itemHeight: 10, // 设置高度

            data: legendData
          },
          grid: {
            left: '5%',
            right: '5%',
            bottom: '20%',
            top: '25%'
          },

          yAxis: {
            type: 'value',
            axisLabel: {
              textStyle: {
                color: '#606266',
                fontSize: '12'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#C0D1E1',
                width: 1

              }
            }
          },
          color: ['#00ACC1', '#3AC7D9', '#86E9D1'],
          series: yData
        }
        myChart.clear()
        myChart.setOption(options)
      })
    },
    getImg3() {
      const myChart = echarts.init(this.$refs.charts3)
      const imgName = this.getDefectTypeName(this.defectCategoryId) + '区站分布柱状分析图TOP10'
      this.getImage('png', myChart, imgName)
    },
    getDefectTypeName(id) {
      let name = ''
      this.defectTypeList.forEach(item => {
        if (item.id === id) {
          name = item.categoryName
        }
      })
      return name
    },
    getDeptName(id) {
      let name = ''
      this.deptList_dw.forEach(item => {
        if (item.deptNo === id) {
          name = item.deptName
        }
      })
      return name
    },
    getImage(imgType, myChart, imgName) {
      var url = myChart.getConnectedDataURL({
        pixelRatio: 2, // 导出的图片分辨率比率,默认是1
        backgroundColor: '#fff', // 图表背景色
        excludeComponents: [
          // 保存图表时忽略的工具组件,默认忽略工具栏
          'toolbox'
        ],
        type: imgType // 图片类型支持png和jpeg
      })
      var $a = document.createElement('a')
      var type = imgType
      $a.download = imgName
      $a.target = '_blank'
      $a.href = url
      // Chrome and Firefox
      if (typeof MouseEvent === 'function') {
        var evt = new MouseEvent('click', {
          view: window,
          bubbles: true,
          cancelable: false
        })
        $a.dispatchEvent(evt)
      } else {
        var base64 = {
          dataURL: url,
          type: imgType,
          ext: imgType
        }
        var blob = this.convertBase64UrlToBlob(base64)
        // 下载
        window.navigator.msSaveBlob(
          blob,
          myChart.getOption().title[0].text + '.' + imgType
        )
      }
    },
    convertBase64UrlToBlob(base64) {
      var parts = base64.dataURL.split(';base64,')
      var contentType = parts[0].split(':')[1]
      var raw = window.atob(parts[1])
      var rawLength = raw.length
      var uInt8Array = new Uint8Array(rawLength)
      for (var i = 0; i < rawLength; i++) {
        uInt8Array[i] = raw.charCodeAt(i)
      }
      return new Blob([uInt8Array], { type: contentType })
    },
    getYearList() {
      var start = this.times.startYear ? parseInt(this.times.startYear) : (new Date().getFullYear() - 3)
      var end = this.times.endYear ? parseInt(this.times.endYear) : new Date().getFullYear()
      this.listQuery.yearList = []
      for (var i = start; i <= end; i++) {
        this.listQuery.yearList.push(i.toString())
      }
    }
  }

}
</script>
<style lang="scss" scoped>
.content {
  padding: 0 20px;
  width: 100%;
  height: 100%;
  padding-bottom: 20px;
}
.header {
  width: 100%;
  height: 70px;
  display: flex;
  align-items: center;
}
.form-top-p {
  width: 220px;
  margin-right: 15px;
  margin-bottom: 0;
}
/deep/.el-input--medium .el-input__inner {
  height: 30px;
  line-height: 30px;
}
/deep/.el-range-editor--medium.el-input__inner {
  height: 30px;
  line-height: 30px;
}
.main {
  height: calc(100% - 80px);
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}
.main_div {
  height: 32%;
  width: 100%;
}
/deep/.box-card {
  width: 100%;
  height: 100%;
  margin: 0 !important;
  float: none;
  background: #ffffff;
  box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.04);
  border-radius: 6px;
  border: 0;
}
/deep/.el-card__header {
  padding: 0;
  height: 60px;
  padding: 0 20px;
  border: 0;
  box-shadow: 0px 0px 10px 5px rgba(0, 47, 138, 0.06);
  background-color: #fff !important;
}
/deep/.el-card__body {
  padding: 0;
  width: 100%;
  height: calc(100% - 60px);
  border: 0;
}
.cardMain {
  width: 100%;
  height: 100%;
}
</style>
